package com.itheima.practise;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.junit.Test;

import java.util.HashMap;

public class UserTest {
    private ObjectMapper mapper = new ObjectMapper();
    @Test
    public void test01() throws Exception {
        //将java对象转化成json对象
        User user = new User("张三",23);
        String json = mapper.writeValueAsString(user);
        System.out.println("json"+json);

        //将json对象转化成java对象,将json对象转化成指定的java对象
        User user1 = mapper.readValue(json, User.class);
        System.out.println(user1);
    }
    @Test
    public void test02() throws Exception {
       //将集合对象转化成json对象,泛型中没有自定义对象
        HashMap<String,String> map = new HashMap<>();
        map.put("姓名","张三");
        map.put("性别","男");
        String json = mapper.writeValueAsString(map);
        System.out.println("json字符串"+json);
        //json转化成map集合，泛型中没有自定义对象
        HashMap<String ,String > map2 = mapper.readValue(json, HashMap.class);
        System.out.println("java对象:"+map2);
    }
    @Test
    public void test03() throws Exception {
         //将集合对象转化成json对象,泛型中有自定义对象
        User user = new User("张三",23);
        User user1 = new User("李四",24);
        HashMap<String, User> map3 = new HashMap<>();
        map3.put("一班",user);
        map3.put("二班",user1);
        String json = mapper.writeValueAsString(map3);
        System.out.println("json"+json);
        //json转化map<String,User>,因为泛型中有自定义对象，需要使用TypeReference这个类，却这个类是个抽象类
        HashMap<String,User> map4 = mapper.readValue(json,new TypeReference<HashMap<String,User>>(){});
        System.out.println(map4);
        //list集合的操作方法是一样的
    }
}
